<template>
  <div class="relative">
    <!-- logicFlow  -->
    <div class="logicFlow-box color-info" ref="logicFlowContainer"></div>
    <!-- 属性弹窗 -->
    <transition
      name="right-transform"
      mode="out-in"
      @before-leave="propertyShow = false"
    >
      <propertyPannel
        :rouleOptions="rouleOptions"
        v-if="propertyShow"
        @close="closeProperty"
        @saveProperty="saveProperty"
        @deleteNode="deleteNode"
        :propertyData="propertyData"
      />
    </transition>
  </div>
</template>

<script>
import { flowGetRoleList } from "@/api";
import LogicFlow from "@logicflow/core";
import {
  Menu, //菜单
  Control, //控制面板
  DndPanel,
  SelectionSelect
} from "@logicflow/extension"; //控制面板

import "@logicflow/core/dist/style/index.css";
import "@logicflow/extension/lib/style/index.css";
import { dndPannel, styleConfig } from "./utils";
import propertyPannel from "./panel/propertyPannel/index.vue";
import htmlTask from "./task/htmlTask";
import UserTask from "./task/userTask";
import { deflate } from "three/examples/jsm/libs/fflate.module";
LogicFlow.use(Menu);
LogicFlow.use(Control);
LogicFlow.use(DndPanel);
LogicFlow.use(SelectionSelect);

export default {
  components: { propertyPannel },
  data() {
    return {
      lf: null,
      propertyShow: false,
      rouleOptions: [],
      propertyData: {} //属性data
    };
  },
  props: {
    /**
     * @name 是否只浏览模式
     */
    isSilentMode: {
      type: Boolean,
      default: false
    },
    /**
     * @name 初始化数据
     */
    flowData: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  destroyed() {
    console.log("消失了");
    this.lf = null;
    this.propertyShow = false;
  },
  created() {
    this.getRoleList();
  },
  mounted() {
    this.initFlow(); //初始化
    if (this.isSilentMode) {
      //只看模式
    } else {
      // 控制面板
      this.flowControl();
      // 拖拽面板
      this.flowDndPanel();
      //新增节点事件
      this.nodeDndAdd();
      //   点击节点事件
      this.nodeClick();
    }
    const { transformModel, height, width } = this.lf.graphModel;
    // console.log("transformModel------------");
    // console.log(this.lf.graphModel);
    // console.log(height, width);
    // 注册
    this.lf.register(UserTask);
    this.lf.register(htmlTask);
    this.lf.render(this.flowData);
  },
  methods: {
    /**
     * @name 获取角色列表
     */
    async getRoleList() {
      let params = {
        page: 1,
        size: 200
      };
      let { data } = await flowGetRoleList(params);
      data?.list?.forEach(e => {
        this.rouleOptions.push({ value: e.id.toString(), label: e.roleName });
      });
    },
    // 初始化流程
    initFlow() {
      this.lf = new LogicFlow({
        container: this.$refs.logicFlowContainer,
        grid: {
          type: "mesh",
          size: 15,
          config: {
            color: "#2E3D5C"
            //   thickness: 1
          }
        },
        keyboard: {
          enabled: true
        },
        isSilentMode: this.isSilentMode, // 仅仅可以浏览，不可进行节点和文本编辑
        background: {
          backgroundColor: "#2b364a"
        },
        plugins: this.isSilentMode
          ? []
          : [DndPanel, SelectionSelect, Menu, Control], //插件
        style: styleConfig(),
        keyboard: {
          enabled: true,
          shortcuts: [
            {
              keys: ["backspace"],
              callback: () => {
                const r = window.confirm("确定要删除吗？");
                if (r) {
                  console.log(this.lf);
                  const elements = this.lf.getSelectElements(true);
                  this.lf?.clearSelectElements();
                  elements.edges.forEach(edge =>
                    this.lf.deleteEdge(edge.id || "")
                  );
                  elements.nodes.forEach(node =>
                    this.lf.deleteNode(node.id || "")
                  );
                  this.closeProperty();
                }
              }
            }
          ]
        }
      });
    },
    /**
     * @name 控制面板显示
     */
    flowControl() {
      this.lf.extension.control.addItem({
        iconClass: "el-icon-info",
        title: "",
        text: "查看数据",
        onMouseEnter: (lf, ev) => {
          //   const position = this.lf.getPointByClient(ev.x, ev.y);
          //   this.lf.extension.miniMap.showMiniMap.show(
          //     position.domOverlayPosition.x - 120,
          //     position.domOverlayPosition.y + 35
          //   );
        },
        onClick: (lf, ev) => {
          this.getNodesEdges();
          const position = this.lf.getPointByClient(ev.x, ev.y);
          this.lf.extension.miniMap.show(
            position.domOverlayPosition.x - 120,
            position.domOverlayPosition.y + 35
          );
        }
      });
    },
    /**
     * @name 拖拽面板
     */
    flowDndPanel() {
      this.lf.extension.dndPanel.setPatternItems([
        {
          label: "选区",
          icon:
            "",
          callback: () => {
            this.lf.extension.selectionSelect.openSelectionSelect();
            this.lf.once("selection:selected", () => {
              this.lf.extension.selectionSelect.closeSelectionSelect();
            });
          }
        },
        ...dndPannel()
      ]);
    },
    /**
     * @name 拖拽生成节点
     */
    nodeDndAdd() {
      this.lf.on("node:dnd-add", data => {
        this.propertyData = {};
      });
    },
    /**
     * @name 点击节点
     */
    nodeClick() {
      //节点点击事件
      this.lf.on("node:click", data => {
        console.log("data");
        console.log(data);
        let nodeData = data.data;
        let nodeObj = {
          ...nodeData,
          textName: nodeData.text.value
        };
        let formObj = {
          ...nodeData?.properties
        };
        if (this.propertyShow && nodeData.id != this.propertyData.id) {
          this.propertyShow = false;
          setTimeout(() => {
            this.propertyData = Object.assign(nodeObj, formObj);
            this.propertyShow = true;
          }, 500);
          return false;
        }
        this.propertyData = Object.assign(nodeObj, formObj);
        this.propertyShow = true;
      });
    },
    /**
     * @name 删除节点
     */
    deleteNode(data) {
      this.lf.deleteNode(data.id);
    },
    getNodesEdges() {
      return this.lf.getGraphData();
      //   console.log(this.lf.getGraphData());
      //   this.lf.getGraphData();
    },
    closeProperty() {
      this.propertyShow = false;
    },
    saveProperty(data) {
      console.log("data");
      console.log(data);
      this.lf.updateText(data.id, data.textName); //更新名称
      this.lf.changeNodeType(data.id, data.type); //类型更新
      let dataObj = Object.assign({}, data);
      dataObj.handelUser = dataObj.handelUser.toString();
      delete dataObj.id;
      delete dataObj.type;
      delete dataObj.textName;
      this.lf.setProperties(data.id, dataObj);
    }
  }
};
</script>

<style scoped>
.logicFlow-box {
  width: 100%;
  height: 750px;
}
</style>
